package com.xxx.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxx.common.Result;
import com.xxx.pojo.Standards;
import com.xxx.service.StandardsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/standards")
public class StandardsController {

    @Autowired
    private StandardsService standardsService;

    /**
     * 新增标准
     * @param standards
     * @return
     */
    @Transactional
    @PostMapping("/save")
    @PreAuthorize("hasAnyAuthority('sys:add:standards')")
    public Result save(@RequestBody Standards standards){
        standards.setUpdateTime(LocalDateTime.now());
        log.info("Standards:{}",standards);

        boolean b = standardsService.save(standards);
        return b ? Result.success("保存成功") : Result.error("保存失败");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/del/{id}")
    @PreAuthorize("hasAnyAuthority('sys:deleted:standards')")
    public Result delById(@PathVariable Integer id){
        boolean b = standardsService.removeById(id);

        return b ? Result.success("删除成功") : Result.error("删除失败");
    }

    /**
     * 修改
     * @param standards
     * @return
     */
    @Transactional
    @PutMapping("/update")
    @PreAuthorize("hasAnyAuthority('sys:update:standards')")
    public Result update(@RequestBody Standards standards){

        standards.setUpdateTime(LocalDateTime.now());

        boolean b = standardsService.updateById(standards);
        return b ? Result.success("更新成功") : Result.error("更新失败");

    }

    @GetMapping("/get-standards")
    @PreAuthorize("hasAnyAuthority('sys:select:standards')")
    public Result getStandards(Integer pageNo, Integer pageSize,String scope, String metrics){

        IPage iPage = new Page(pageNo,pageSize);

        iPage = standardsService.page(iPage, new LambdaQueryWrapper<Standards>()
                .like(scope != null && scope.trim() != "", Standards::getScope, scope)
                .like(metrics != null && metrics.trim() != "", Standards::getMetrics, metrics));

        return iPage.getRecords().size() != 0 ? Result.success("查询成功", iPage) : Result.error("没有查到符合数据");
    }


}
